package com.cnaaa.pay.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

/**
 * 2018/10/31 Create by 郭文梁
 * JAXBXmlUtil
 * 使用JAXB实现的XML工具类
 *
 * @author 郭文梁
 * @date 2018/10/31
 */
public class JAXBXmlUtil {
    public static String toXML(Object ele) {
        Marshaller marshaller = getMarshaller(ele.getClass());
        if (marshaller == null) {
            throw new IllegalStateException("Could not get JAXB Marshaller.");
        }
        StringWriter writer = new StringWriter();
        try {
            marshaller.marshal(ele, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Marshaller getMarshaller(Class<?> clazz) {
        try {
            JAXBContext context = getJaxbContext(clazz);
            if (context == null) {
                return null;
            }
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            return marshaller;
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static JAXBContext getJaxbContext(Class<?> clazz) {
        try {
            return JAXBContext.newInstance(clazz);
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }
}
